// 读取 cookie 的函数
function getCookie(name) {
    const cookies = document.cookie.split('; ');
    for (let i = 0; i < cookies.length; i++) {
        const parts = cookies[i].split('=');
        if (parts[0] === name) {
            return decodeURIComponent(parts[1]);
        }
    }
    return null;
}

// 当前学生 ID - 从 cookie 获取
let currentStudentId = getCookie('user_id');
console.log('当前学生 ID:', currentStudentId);
if (!currentStudentId || isNaN(currentStudentId)) {
    currentStudentId = null;
} else {
    currentStudentId = parseInt(currentStudentId, 10);
}

// 当前学生姓名 - 从 cookie 获取，假设存储姓名的 cookie 名为 student_name
let currentStudentName = getCookie('student_name');
if (!currentStudentName) {
    currentStudentName = null;
}

// 封装通用的 fetch 请求函数
async function fetchData(url, method = 'GET', body = null) {
    const options = {
        method,
        headers: {
            'Content-Type': 'application/json'
        }
    };

    if (body) {
        options.body = JSON.stringify(body);
    }

    try {
        const response = await fetch(url, options);
        if (!response.ok) {
            // 尝试解析错误信息
            try {
                const errorData = await response.json();
                throw new Error(errorData.msg || `请求失败，状态码: ${response.status}`);
            } catch (e) {
                throw new Error(`请求失败，状态码: ${response.status}`);
            }
        }
        return response.json();
    } catch (error) {
        console.error('数据获取错误:', error);
        throw error;
    }
}

// 获取学生信息
async function fetchStudentInfo() {
    if (!currentStudentId) {
        console.error('未获取到有效的学生 ID');
        document.getElementById('studentName').textContent = '未知用户';
        return;
    }

    try {
        const data = await fetchData(`/student/${currentStudentId}`);
        if (data.code === 200) {
            const student = data.data;
            currentStudentName = student.sname;
            document.getElementById('studentName').textContent = student.sname;
        } else {
            console.error('获取学生信息失败:', data.msg);
            document.getElementById('studentName').textContent = '未知用户';
        }
    } catch (error) {
        console.error('获取学生信息出错:', error);
        document.getElementById('studentName').textContent = '未知用户';
    }
}

// 加载我的课程
async function loadMyCourses() {
    if (!currentStudentId) {
        alert('学生 ID 无效，请重新登录');
        return;
    }

    const container = document.getElementById('my-courses-container');
    const table = container.querySelector('table');
    const loading = container.querySelector('.loading');
    const errorDiv = document.getElementById('my-courses-error');

    // 显示加载中，隐藏表格和错误信息
    loading.style.display = 'block';
    table.style.display = 'none';
    errorDiv.style.display = 'none';

    try {
        const data = await fetchData(`/student/courses/${currentStudentId}`);
        loading.style.display = 'none';

        if (data.code === 200) {
            renderMyCourses(data.data);
            table.style.display = 'table';
        } else {
            errorDiv.textContent = data.msg || '获取课程列表失败';
            errorDiv.style.display = 'block';
        }
    } catch (error) {
        loading.style.display = 'none';
        errorDiv.textContent = '网络错误，请稍后重试';
        errorDiv.style.display = 'block';
        console.error('获取我的课程出错:', error);
    }
}

// 渲染我的课程
function renderMyCourses(courses) {
    const tableBody = document.getElementById('my-courses-table');
    tableBody.innerHTML = '';

    if (!courses || courses.length === 0) {
        tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center;">暂无课程数据</td></tr>';
        return;
    }

    courses.forEach(course => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${course.courseName || '未知课程'}</td>
            <td>${course.chours || 0}课时</td>
            <td>${course.teacherName || '未知教师'}</td>
            <td>${course.status || '已选'}</td>
            <td>
                <button class="action-btn drop-btn"
                        data-course-id="${course.courseId}"
                        data-course-name="${course.courseName || '未知课程'}">
                    退课
                </button>
            </td>
        `;
        tableBody.appendChild(row);
    });

    // 绑定退课按钮事件
    document.querySelectorAll('.drop-btn').forEach(btn => {
        btn.addEventListener('click', function () {
            const courseId = this.getAttribute('data-course-id');

            if (!courseId || isNaN(courseId)) {
                alert('课程 ID 无效，请刷新页面重试');
                return;
            }
            const courseName = this.getAttribute('data-course-name');

            document.getElementById('confirm-drop-course-name').textContent = courseName;
            document.getElementById('confirmDrop').setAttribute('data-course-id', courseId);

            document.getElementById('dropCourseModal').style.display = 'flex';
        });
    });
}

// 加载我的成绩
async function loadMyScores() {
    if (!currentStudentId) {
        alert('学生 ID 无效，请重新登录');
        return;
    }

    const container = document.getElementById('my-scores-container');
    const table = container.querySelector('table');
    const loading = container.querySelector('.loading');
    const errorDiv = document.getElementById('my-scores-error');

    // 显示加载中，隐藏表格和错误信息
    loading.style.display = 'block';
    table.style.display = 'none';
    errorDiv.style.display = 'none';

    try {
        const data = await fetchData(`/student/scores/${currentStudentId}`);
        loading.style.display = 'none';

        if (data.code === 200) {
            renderMyScores(data.data);
            table.style.display = 'table';
        } else if (data.code === 0 && data.msg === "教师还未上传成绩") {
            renderMyScores([]);
            table.style.display = 'table';
        } else {
            errorDiv.textContent = data.msg || '获取成绩失败';
            errorDiv.style.display = 'block';
        }
    } catch (error) {
        loading.style.display = 'none';
        errorDiv.textContent = '网络错误，请稍后重试';
        errorDiv.style.display = 'block';
        console.error('获取我的成绩出错:', error);
    }
}

// 渲染我的成绩
function renderMyScores(scores) {
    const tableBody = document.getElementById('my-scores-table');
    tableBody.innerHTML = '';

    if (!scores || scores.length === 0) {
        tableBody.innerHTML = '<tr><td colspan="4" style="text-align: center;">暂无成绩数据</td></tr>';
        return;
    }

    scores.forEach(score => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${score.courseName || '未知课程'}</td>
            <td>${score.score || '暂无'}</td>
            <td>${score.credit || '2'}</td>
            <td>${score.score !== undefined && score.score !== null ? (score.score >= 60 ? '通过' : '不通过') : '暂无'}</td>
        `;
        tableBody.appendChild(row);
    });
}

// 加载可选课程
async function loadAvailableCourses() {
    if (!currentStudentId) {
        alert('学生 ID 无效，请重新登录');
        return;
    }

    const container = document.getElementById('available-courses-container');
    const courseList = document.getElementById('available-courses-list');
    const loading = container.querySelector('.loading');
    const errorDiv = document.getElementById('available-courses-error');

    // 显示加载中，隐藏课程列表和错误信息
    loading.style.display = 'block';
    courseList.style.display = 'none';
    errorDiv.style.display = 'none';

    try {
        // 同时获取所有课程和学生已选课程
        const [allCoursesData, myCoursesData] = await Promise.all([
            fetchData('/course/query'),
            fetchData(`/student/courses/${currentStudentId}`)
        ]);

        loading.style.display = 'none';

        if (allCoursesData.code === 200 && myCoursesData.code === 200) {
            // 获取已选课程的ID列表
            const enrolledCourseIds = myCoursesData.data.map(course => course.courseId);

            // 过滤掉已选课程
            const availableCourses = allCoursesData.data.filter(course =>
                !enrolledCourseIds.includes(course.id)
            );

            renderAvailableCourses(availableCourses);
            courseList.style.display = 'grid';
        } else {
            const errorMsg = allCoursesData.msg || myCoursesData.msg || '获取可选课程失败';
            errorDiv.textContent = errorMsg;
            errorDiv.style.display = 'block';
        }
    } catch (error) {
        loading.style.display = 'none';
        errorDiv.textContent = '网络错误，请稍后重试';
        errorDiv.style.display = 'block';
        console.error('获取可选课程出错:', error);
    }
}

// 渲染可选课程
function renderAvailableCourses(courses) {
    const coursesList = document.getElementById('available-courses-list');
    coursesList.innerHTML = '';

    if (!courses || courses.length === 0) {
        coursesList.innerHTML = '<div class="no-data">当前没有可选课程</div>';
        return;
    }

    courses.forEach(course => {
        const courseCard = document.createElement('div');
        courseCard.className = 'course-card';
        courseCard.innerHTML = `
            <div class="course-name">${course.cname || '未知课程'}</div>
            <div class="course-info">课时: ${course.chours || 0}课时</div>
            <div class="course-info">授课教师: ${course.teacherName || '未知教师'}</div>
            <div class="course-info">状态: ${course.status || '未选'}</div>
            <button class="action-btn select-btn"
                    data-course-id="${course.id}"
                    data-course-name="${course.cname || '未知课程'}"
                    style="margin-top: 10px;">
                选课
            </button>
        `;
        coursesList.appendChild(courseCard);
    });

    // 绑定选课按钮事件
    document.querySelectorAll('.select-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const courseId = this.getAttribute('data-course-id');
            const courseName = this.getAttribute('data-course-name');

            document.getElementById('confirm-course-name').textContent = courseName;
            document.getElementById('confirmSelect').setAttribute('data-course-id', courseId);

            document.getElementById('selectCourseModal').style.display = 'flex';
        });
    });
}

// 菜单切换
const menuItems = document.querySelectorAll('.menu-item');
menuItems.forEach(item => {
    item.addEventListener('click', function() {
        // 移除所有 active 类
        menuItems.forEach(i => i.classList.remove('active'));
        // 添加当前 active 类
        this.classList.add('active');

        // 隐藏所有页面
        document.querySelectorAll('.page-content').forEach(page => {
            page.style.display = 'none';
        });

        // 显示当前页面
        const pageId = this.getAttribute('data-page') + '-page';
        document.getElementById(pageId).style.display = 'block';

        // 根据页面加载数据
        if (!currentStudentId) {
            alert('学生 ID 无效，请重新登录');
            return;
        }
        switch(this.getAttribute('data-page')) {
            case 'my-courses':
                loadMyCourses();
                break;
            case 'my-scores':
                loadMyScores();
                break;
            case 'select-courses':
                loadAvailableCourses();
                break;
        }
    });
});

// 默认加载我的课程
document.addEventListener('DOMContentLoaded', async function() {
    if (currentStudentId) {
        await fetchStudentInfo();
        loadMyCourses();
    } else {
        alert('未获取到有效的学生 ID，请重新登录');
    }

    // 全局绑定确认选课事件（只绑定一次）
    document.getElementById('confirmSelect').addEventListener('click', async function() {
        const confirmBtn = this;
        confirmBtn.disabled = true; // 禁用按钮防止重复点击

        try {
            if (!currentStudentId) {
                alert('学生 ID 无效，请重新登录');
                document.getElementById('selectCourseModal').style.display = 'none';
                return;
            }

            const courseId = this.getAttribute('data-course-id');

            // 准备选课数据 - 发送单个对象
            const selection = {
                studentId: currentStudentId,
                courseId: parseInt(courseId),
                date_time: new Date().toISOString()
            };

            const data = await fetchData('/student/courses', 'POST', [selection]);
            document.getElementById('selectCourseModal').style.display = 'none';

            if (data.code === 200) {
                alert('选课成功');
                loadMyCourses(); // 刷新我的课程列表
                loadAvailableCourses(); // 刷新可选课程列表
            } else {
                alert(data.msg || '选课失败');
            }
        } catch (error) {
            console.error('选课出错:', error);
            alert(`选课失败: ${error.message || '请稍后重试'}`);
        } finally {
            confirmBtn.disabled = false; // 重新启用按钮
        }
    });

    // 全局绑定确认退课事件（只绑定一次）
    document.getElementById('confirmDrop').addEventListener('click', async function() {
        const confirmBtn = this;
        confirmBtn.disabled = true; // 禁用按钮防止重复点击

        try {
            if (!currentStudentId) {
                alert('学生 ID 无效，请重新登录');
                document.getElementById('dropCourseModal').style.display = 'none';
                return;
            }

            // 确保课程ID是数字类型
            const courseId = parseInt(this.getAttribute('data-course-id'));

            if (isNaN(courseId)) {
                alert('课程 ID 无效，请刷新页面重试');
                document.getElementById('dropCourseModal').style.display = 'none';
                return;
            }

            // 使用数字类型的课程ID
            const data = await fetchData(`/student/courses/delete?student_id=${currentStudentId}&course_id=${courseId}`);
            document.getElementById('dropCourseModal').style.display = 'none';

            if (data.code === 200 && data.data) {
                alert('退课成功');
                loadMyCourses(); // 刷新课程列表
            } else {
                alert(data.msg || '退课失败');
            }
        } catch (error) {
            console.error('退课出错:', error);
            alert(`退课失败: ${error.message || '请稍后重试'}`);
        } finally {
            confirmBtn.disabled = false; // 重新启用按钮
        }
    });
});

// 退出登录
document.getElementById('logoutBtn').addEventListener('click', function() {
    if (confirm('确定要退出登录吗？')) {
        // 清除 cookie
        document.cookie = "user_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
        document.cookie = "student_name=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
        // 重置变量
        currentStudentId = null;
        currentStudentName = null;
        document.getElementById('studentName').textContent = '未知用户';
        // 跳转到 index.html
        window.location.href = 'index.html';
    }
});

// 选课模态框控制
const selectCourseModal = document.getElementById('selectCourseModal');
const closeSelectModal = document.getElementById('closeSelectModal');
const cancelSelect = document.getElementById('cancelSelect');

closeSelectModal.addEventListener('click', function() {
    selectCourseModal.style.display = 'none';
});

cancelSelect.addEventListener('click', function() {
    selectCourseModal.style.display = 'none';
});

// 退课模态框控制
const dropCourseModal = document.getElementById('dropCourseModal');
const closeDropModal = document.getElementById('closeDropModal');
const cancelDrop = document.getElementById('cancelDrop');

closeDropModal.addEventListener('click', function() {
    dropCourseModal.style.display = 'none';
});

cancelDrop.addEventListener('click', function() {
    dropCourseModal.style.display = 'none';
});

// 点击页面其他地方关闭模态框
window.addEventListener('click', function(event) {
    if (event.target === selectCourseModal) {
        selectCourseModal.style.display = 'none';
    }
    if (event.target === dropCourseModal) {
        dropCourseModal.style.display = 'none';
    }
});